﻿package com.firewolf.spring.transaction.byxml;

import org.springframework.jdbc.core.JdbcTemplate;

public class BookDaoImpl implements IBookShopDao{
	
	private JdbcTemplate jdbcTemplate = null;
	
	@Override
	public int findBookPriceById(String bookId) {
		String sql  = "select price from book where isbn = ? ";
		int price = jdbcTemplate.queryForObject(sql, Integer.class, bookId);
		return price;
	}

	/**
	 * 更新库存
	 */
	@Override
	public void updateBookStock(String bookId) {
		String sql1 = "select bookstock from book_stock where isbn = ? ";
		int bookStock = jdbcTemplate.queryForObject(sql1, Integer.class, bookId);
		if(bookStock == 0)
			throw new BookStockException("库存不足！");
		String sql = "update book_stock set bookstock = bookstock-1 where isbn = ? ";
		jdbcTemplate.update(sql,bookId);
	}

	/**
	 * 更新余额
	 */
	@Override
	public void updateUserAccount(String username,int price) {
		String sql1 = "select balance from account where username = ? ";
		int balance = jdbcTemplate.queryForObject(sql1, Integer.class,username);
		if(balance < price){
			throw new UserAccountException("余额不足！");
		}
		String sql = "update account set balance = (balance-?) where username=? ";
		jdbcTemplate.update(sql, price,username);
	}

	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

}
